package com.qd.panda.service.stroke;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.cdqidi.util.SpringContextHolder;
import com.qd.common.panda.domain.entity.carpark.CarParkInfoDTO;
import com.qd.common.panda.domain.entity.stroke.UserStrokeConfirmDTO;
import com.qd.common.panda.domain.entity.stroke.UserStrokeConfirmVO;
import com.qd.panda.mapper.stroke.UserStrokeConfirmMapper;
import com.qd.panda.model.CarPark;
import com.qd.panda.model.UserStrokeConfirm;
import com.qd.panda.service.park.CarParkService;
import com.qd.system.model.BaseUserInfo;
import com.qd.system.service.dict.MbUtil;
import com.qd.system.service.user.BaseUserInfoService;
import com.qd.system.service.user.UserOperatorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 行程确认
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class UserStrokeConfirmService extends BaseService<UserStrokeConfirmMapper, UserStrokeConfirm> {

    private static final String PREFIX_ID = "panda_user_stroke_confirm_sid_{0}";
    private static final String PREFIX_UNIQUE_PANDA_USER_SID_AND_DIRECTION = "panda_user_stroke_confirm_sid_{0}_direction_{1}";

    private final BaseUserInfoService baseUserInfoService;
    private final CarParkService carParkService;

    private final RedisTemplateUtil<UserStrokeConfirm> redisTemplateUtil;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserStrokeConfirmDTO save(UserStrokeConfirmDTO dto) {
        checkUnique(dto);
        final UserStrokeConfirm model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);

            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserStrokeConfirmDTO update(UserStrokeConfirmDTO dto) {
        checkUnique(dto);
        final UserStrokeConfirm historyModel = Optional.ofNullable(getById(dto.getCid())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final UserStrokeConfirm model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(model);
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 删除，单个
     *
     * @param cid 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String cid) {
        final UserStrokeConfirm model = Optional.ofNullable(getById(cid)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(cid)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(UserStrokeConfirmDTO dto) {
        final QueryWrapper<UserStrokeConfirm> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 查询今天有没有行程确认记录
     *
     * @param dto 查询参数
     * @return true or false
     */
    public boolean isExistsInCurrentDay(UserStrokeConfirmDTO dto) {
        final QueryWrapper<UserStrokeConfirm> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("park_id", dto.getParkId());
        queryWrapper.eq("user_id", dto.getUserId());
        queryWrapper.eq("plate_number", dto.getPlateNumber());
        queryWrapper.eq("direction", dto.getDirection());
        queryWrapper.eq("confirm", dto.getConfirm());
        queryWrapper.apply("date_format(scan_time,'%Y-%m-%d') = {0}", dto.getScanTime().toLocalDate());
        boolean b = super.getBaseMapper().exists(queryWrapper);
        queryWrapper.clear();
        return b;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param cid 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String cid) {
        boolean exists = false;
        if (StringUtils.hasLength(cid)) {
            final UserStrokeConfirm model = getById(cid);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param cid 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserStrokeConfirm getById(String cid) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, cid);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(cid), UserStrokeConfirm.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param cid 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserStrokeConfirmDTO getByIdDto(String cid) {
        return Optional.ofNullable(getById(cid)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserStrokeConfirm getOne(UserStrokeConfirmDTO dto) {
        final QueryWrapper<UserStrokeConfirm> queryWrapper = createQueryWrapper(dto);
        UserStrokeConfirm model = super.getOne(queryWrapper, false);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserStrokeConfirmDTO getOneDto(UserStrokeConfirmDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<UserStrokeConfirm> getList(UserStrokeConfirmDTO dto) {
        final QueryWrapper<UserStrokeConfirm> queryWrapper = createQueryWrapper(dto);
        final List<UserStrokeConfirm> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<UserStrokeConfirmDTO> getListDto(UserStrokeConfirmDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<UserStrokeConfirmVO> page(Page<UserStrokeConfirm> page, UserStrokeConfirmDTO dto) {
        final QueryWrapper<UserStrokeConfirm> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasLength(dto.getParkId())) {
            queryWrapper.eq("uc.park_id", dto.getParkId());
        }
        if (StringUtils.hasLength(dto.getMobile())) {
            queryWrapper.eq("b.mobile", dto.getMobile());
        }
        if (StringUtils.hasLength(dto.getPlateNumber())) {
            queryWrapper.eq("uc.plate_number", dto.getPlateNumber());
        }
        if (null != dto.getDirection()) {
            queryWrapper.eq("uc.direction", dto.getDirection());
        }
        if (null != dto.getConfirm()) {
            queryWrapper.eq("uc.confirm", dto.getConfirm());
        }
        if (StringUtils.hasLength(dto.getBeginTime())) {
            queryWrapper.apply("date_format(uc.scan_time,'%Y-%m-%d') >= {0}", dto.getBeginTime());
        }
        if (StringUtils.hasLength(dto.getEndTime())) {
            queryWrapper.apply("date_format(uc.scan_time,'%Y-%m-%d') <= {0}", dto.getEndTime());
        }
        queryWrapper.orderByAsc("uc.park_id");
        queryWrapper.orderByAsc("uc.scan_time");
        queryWrapper.orderByAsc("uc.direction");
        queryWrapper.orderByAsc("uc.confirm");

        UserOperatorService.buildInSql(dto, queryWrapper);
        final IPage<UserStrokeConfirmVO> iPage = baseMapper.page(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 根据唯一性索引获得数据
     * <p>
     * param sid
     * param direction
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public UserStrokeConfirm getUniqueBySidAndDirection(String sid, Integer direction) {
        final QueryWrapper<UserStrokeConfirm> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sid", sid);
        queryWrapper.eq("direction", direction);
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_USER_SID_AND_DIRECTION, sid, direction);
        final UserStrokeConfirm model = redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getOne(queryWrapper, false), UserStrokeConfirm.class);
        queryWrapper.clear();
        return model;
    }

    /**
     * 验证唯一性索引
     *
     * @param dto 页面对象
     */
    private void checkUnique(UserStrokeConfirmDTO dto) {
        UserStrokeConfirm model = getUniqueBySidAndDirection(dto.getSid(), dto.getDirection());
        if (null != model) {
            checkUnique(dto, model);
        }
    }

    /**
     * 验证唯一性索引
     *
     * @param dto   页面对象
     * @param model 根据约束字段查询出来的数据库对象
     */
    private void checkUnique(UserStrokeConfirmDTO dto, UserStrokeConfirm model) {
        if (!StringUtils.hasLength(dto.getCid())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
        if (!dto.getCid().equals(model.getCid())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(UserStrokeConfirm model) {
        if (null == model) {
            return;
        }
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getCid());
        redisTemplateUtil.deleteByKey(key);
        key = RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_USER_SID_AND_DIRECTION, model.getSid(), model.getDirection());
        redisTemplateUtil.deleteByKey(key);
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public UserStrokeConfirmDTO modelToDto(UserStrokeConfirm model) {
        if (null == model) {
            return null;
        }
        final UserStrokeConfirmDTO dto = new UserStrokeConfirmDTO();
        dto.setCid(model.getCid());
        dto.setSid(model.getSid());
        dto.setScanTime(model.getScanTime());
        dto.setDirection(model.getDirection());
        dto.setConfirmTime(model.getConfirmTime());
        dto.setPersonId(model.getPersonId());
        dto.setParkId(model.getParkId());
        dto.setPlateNumber(model.getPlateNumber());
        dto.setUserId(model.getUserId());
        dto.setOrgId(model.getOrgId());
        dto.setConfirm(model.getConfirm());
        dto.setDoorPostName(model.getDoorPostName());
        dto.setNote(model.getNote());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public UserStrokeConfirm dtoToModel(UserStrokeConfirmDTO dto) {
        if (null == dto) {
            return null;
        }
        final UserStrokeConfirm model = new UserStrokeConfirm();
        model.setCid(dto.getCid());
        model.setSid(dto.getSid());
        model.setScanTime(dto.getScanTime());
        model.setDirection(dto.getDirection());
        model.setConfirmTime(dto.getConfirmTime());
        model.setPersonId(dto.getPersonId());
        model.setParkId(dto.getParkId());
        model.setPlateNumber(dto.getPlateNumber());
        model.setUserId(dto.getUserId());
        model.setOrgId(dto.getOrgId());
        model.setConfirm(dto.getConfirm());
        model.setDoorPostName(dto.getDoorPostName());
        model.setNote(dto.getNote());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(UserStrokeConfirmDTO dto) {
        dto.setMobile(Optional.ofNullable(baseUserInfoService.getById(dto.getUserId())).map(BaseUserInfo::getMobile).orElse(""));
        if(null!=dto.getDirection()){
            dto.setDirectionDisplay(dto.getDirection() == 1 ? "进场" : "离场");
        }
        dto.setParkIdDisplay(carParkService.idToDisplay(dto.getParkId()));
        dto.setConfirmDisplay(MbUtil.idToDisplay(dto.getConfirm()));
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(UserStrokeConfirmVO dto) {
        dto.setDirectionDisplay(dto.getDirection() == 1 ? "进场" : "离场");
        dto.setParkIdDisplay(carParkService.idToDisplay(dto.getParkId()));
        dto.setConfirmDisplay(MbUtil.idToDisplay(dto.getConfirm()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<UserStrokeConfirmDTO> modelToDtoList(List<UserStrokeConfirm> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<UserStrokeConfirm> dtoToModelList(List<UserStrokeConfirmDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<UserStrokeConfirm> createQueryWrapper(UserStrokeConfirmDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<UserStrokeConfirm> createQueryWrapper(UserStrokeConfirmDTO dto, String tableAlias) {
        final QueryWrapper<UserStrokeConfirm> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias)) {
                if (tableAlias.charAt(tableAlias.length() - 1) != '.') {
                    tableAlias += ".";
                }
            }
            if (StringUtils.hasLength(dto.getSid())) {
                queryWrapper.eq(tableAlias + "sid", dto.getSid());
            }
            if (StringUtils.hasLength(dto.getPersonId())) {
                queryWrapper.eq(tableAlias + "person_id", dto.getPersonId());
            }
            if (StringUtils.hasLength(dto.getParkId())) {
                queryWrapper.eq(tableAlias + "park_id", dto.getParkId());
            }
            if (StringUtils.hasLength(dto.getPlateNumber())) {
                queryWrapper.eq(tableAlias + "plate_number", dto.getPlateNumber());
            }
            if (StringUtils.hasLength(dto.getUserId())) {
                queryWrapper.eq(tableAlias + "user_id", dto.getUserId());
            }
            if (StringUtils.hasLength(dto.getOrgId())) {
                queryWrapper.eq(tableAlias + "org_id", dto.getOrgId());
            }
            if (StringUtils.hasLength(dto.getConfirm())) {
                queryWrapper.eq(tableAlias + "confirm", dto.getConfirm());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     */
    public List<UserStrokeConfirm> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<UserStrokeConfirm> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(UserStrokeConfirm::getCid).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    /**
     * 当前行程是否需要门岗确认
     *
     * @param parkId    停车场ID
     * @param sid       行程ID
     * @param direction 1进 2出
     * @return true or false
     */
    public boolean doorCheck(String parkId, String sid, Integer direction) {
        final String confirmIn = Optional.ofNullable(carParkService.getCarParkInfoByRedis(parkId)).map(CarParkInfoDTO::getConfirmIn).orElse(ConstantDto.SF0);
        if (confirmIn.equals(ConstantDto.SF1)) {
            //需要门岗确认
            final UserStrokeConfirm userStrokeConfirm = SpringContextHolder.getBean(UserStrokeConfirmService.class).getUniqueBySidAndDirection(sid, direction);
            //说明当前扫码门岗没有确认，等待门岗确认，此时不能清理
            return null != userStrokeConfirm && userStrokeConfirm.getConfirm().equals(ConstantDto.SF0);
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(String sid, Integer direction, String plateNumber, LocalDateTime scanTime, CarPark carPark, String userId) {
        UserStrokeConfirm confirm = getUniqueBySidAndDirection(sid, direction);
        UserStrokeConfirmDTO userStrokeConfirm = new UserStrokeConfirmDTO();
        if (null == confirm) {
            userStrokeConfirm.setSid(sid);
            userStrokeConfirm.setOrgId(carPark.getPId());
            userStrokeConfirm.setUserId(userId);
            userStrokeConfirm.setConfirm(ConstantDto.SF0);
            userStrokeConfirm.setDirection(direction);
            userStrokeConfirm.setScanTime(scanTime);
            userStrokeConfirm.setParkId(carPark.getPId());
            userStrokeConfirm.setPlateNumber(plateNumber);
            save(userStrokeConfirm);
        } else {
            userStrokeConfirm.setCid(confirm.getCid());
            userStrokeConfirm.setScanTime(scanTime);
            update(userStrokeConfirm);
        }
        userStrokeConfirm.freeData();
    }
}